<template>
  <ul class="ssml-tools">
    <li class="stop-time" @click="insertBreak">
      <SvgList name="zhuanting" /> <span>停顿</span>
    </li>
    <li><SvgList name="fenci" /><span>分词</span></li>
    <li><SvgList name="duoyinzi" /><span>多音字</span></li>
    <li><SvgList name="specialTran" /><span>替换发音</span></li>
    <li class="line-icon"><SvgList name="line" /></li>
    <li @click="startPlay"><SvgList name="start" /></li>
    <li @click="pausePlay"><SvgList name="stop" /></li>
    <li><SvgList name="kuozhan" /></li>
  </ul>
</template>

<script setup lang="ts">
import { setCursorPosition, safeRestoreCursor } from "@/utils/selectionRang";
const props = defineProps<{
  selectConfig: any;
  inputHtml: string;
}>();
const emits = defineEmits(["handleFocus"]);
// 播放状态
const isPlaying = ref(false);
let utterance = null;
function insertBreak() {
  emits("handleFocus");
  // 获取当前选区
  const selection = window.getSelection();
  if (!selection || selection.rangeCount === 0) return;

  const range = selection.getRangeAt(0);

  // 创建 break 元素
  const breakElement = document.createElement("break");
  breakElement.setAttribute("time", "200ms");
  breakElement.style.color = "#1890ff"; // 可选：给标记添加样式
  // 删除选区内容（如果有选中文本）
  range.deleteContents();
  // 插入 break 标记
  range.insertNode(breakElement);
  // 移动光标到标记后面
  range.setStartAfter(breakElement);
  range.collapse(true);
  selection.removeAllRanges();
  selection.addRange(range);
  // setCursorPosition(props.selectConfig);
}
function setPinyin() {}
function startPlay() {
  if (isPlaying.value) return;
  // 提取纯文本（去掉 HTML 标签）
  const text = props.inputHtml.replace(/<[^>]+>/g, "");
  // 构建完整 SSML
  const ssml = `<speak>${text}</speak>`;
  // 调用浏览器语音合成
  utterance = new SpeechSynthesisUtterance();
  utterance.lang = "zh-CN";
  utterance.text = ssml;
  utterance.onstart = () => {
    isPlaying.value = true;
  };
  utterance.onend = () => {
    isPlaying.value = false;
  };

  window.speechSynthesis.speak(utterance);
}
function pausePlay() {
  if (!isPlaying.value) return;
  window.speechSynthesis.pause();
  isPlaying.value = false;
}
</script>

<style lang="scss" scoped>
.text2ssml {
  ul {
    display: flex;
    align-items: center;
    background: $color_2;
    padding: 6px;
    border-radius: 6px;
    li {
      padding: 4px 0;
      display: inline-block;
      width: 54px;
      border-radius: 6px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      cursor: pointer;
    }
    li:hover {
      background: $color_1;
    }
    .line-icon {
      width: 20px;
    }
  }
}
</style>
